﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CastleOfTheDisillusioned.Location.Maps {
	class Node : BoundingBox {
		public bool Taken = false;
		public Cell BelongsTo = null;
		public Cell LeadsTo = null;

		public Node LinkedWith = null;

		public Direction ConnectionType = Direction.Right;

		public Node(double X, double Y, Cell BelongsTo, Direction ConnectionType) {
			this.X = X;
			this.Y = Y;
			this.BelongsTo = BelongsTo;
			this.ConnectionType = ConnectionType;

			this.Width = 0;
			this.Height = 0;
		}

		public bool LinkWith(Node other, Map source) {
			if (CanConnect(other, source)) {
				ConnectNodes(other);
				return true;
			}
			return false;
		}

		private bool CanConnect(Node other, Map source) {
			Cell Candidate = other.BelongsTo;
			
			//Generate new bounding box
			BoundingBox bb = Candidate.Copy();
			double DiffX = this.X - other.X;
			double DiffY = this.Y - other.Y;
			bb.X = this.BelongsTo.X + DiffX;
			bb.Y = this.BelongsTo.Y + DiffY;
			//Shrink everything by 1, to allow a little overlap
			bb.X += 2; bb.Y += 2;
			bb.Width -= 4; bb.Height -= 4;

			//Check for collisions
			foreach (Cell c in source.Cells) {
				if (bb.CollidesWith(c)) {
					return false;
				}
			}
			return true;
		}

		private void ConnectNodes(Node other) {
			//Link the nodes together
			this.Taken = true;
			other.Taken = true;

			this.LeadsTo = other.BelongsTo;
			other.LeadsTo = this.BelongsTo;

			this.LinkedWith = other;
			other.LinkedWith = this;

			//Adjust the other node's position
			double DiffX = this.X - other.X;
			double DiffY = this.Y - other.Y;

			this.LeadsTo.X = this.BelongsTo.X + DiffX;
			this.LeadsTo.Y = this.BelongsTo.Y + DiffY;
		}
	}
}
